"""
Pixiv API数据获取模块
"""
import requests
import json
import time
from typing import Dict, List, Optional
import logging
from config import PIXIV_CONFIG

logger = logging.getLogger(__name__)

class PixivAPI:
    def __init__(self):
        self.session = requests.Session()
        self.session.headers.update(PIXIV_CONFIG["headers"])
        self.cookie = PIXIV_CONFIG.get("cookie", "")

        if self.cookie:
            self.session.headers.update({"Cookie": self.cookie})

    def get_author_info(self, author_id: int) -> Optional[Dict]:
        """
        获取作者信息
        """
        try:
            # Pixiv作者信息API - 尝试不同的API端点
            urls = [
                f"https://www.pixiv.net/ajax/user/{author_id}/profile/all",
                f"https://www.pixiv.net/ajax/user/{author_id}/profile",
                f"https://www.pixiv.net/ajax/user/{author_id}"
            ]

            data = None
            for url in urls:
                response = self.session.get(url)
                if response.status_code == 200:
                    data = response.json()
                    if not data.get("error"):
                        break

            if not data or data.get("error"):
                logger.error(f"获取作者{author_id}信息失败: {data.get('message') if data else 'No response'}")
                return None

            # 调试：打印API返回的数据结构
            logger.debug(f"作者{author_id} API返回: {str(data)[:500]}...")

            # 提取关键信息 - 尝试不同的数据路径
            body = data.get("body", {})

            # 尝试获取用户名
            username = "未知"

            # 先从profile API获取基本信息
            try:
                profile_response = self.session.get(f"https://www.pixiv.net/ajax/user/{author_id}")
                if profile_response.status_code == 200:
                    profile_data = profile_response.json()
                    if not profile_data.get("error"):
                        username = profile_data.get("body", {}).get("name", "未知")
            except:
                pass

            # 如果上面获取失败，尝试其他方式
            if username == "未知":
                if "userData" in body:
                    username = body["userData"].get("name", "未知")
                elif "name" in body:
                    username = body.get("name", "未知")
                elif "novelSeries" in body and len(body["novelSeries"]) > 0:
                    username = body["novelSeries"][0].get("userName", "未知")

            return {
                "author_id": author_id,
                "username": username,
                "profile": body,
                "fetch_time": time.time()
            }

        except Exception as e:
            logger.error(f"获取作者{author_id}信息时出错: {str(e)}")
            return None

    def get_author_illusts(self, author_id: int) -> List[Dict]:
        """
        获取作者作品列表（包括插画和小说）
        """
        try:
            # 先从profile/all获取完整的作品列表
            url = f"https://www.pixiv.net/ajax/user/{author_id}/profile/all"

            response = self.session.get(url)
            if response.status_code != 200:
                logger.error(f"获取作者{author_id}作品列表失败: HTTP {response.status_code}")
                return []

            data = response.json()

            if data.get("error"):
                logger.error(f"获取作者{author_id}作品列表失败: {data.get('message')}")
                return []

            body = data.get("body", {})
            all_works = []

            # 获取插画作品
            if "illusts" in body:
                illust_ids = list(body["illusts"].keys())
                logger.info(f"发现{len(illust_ids)}个插画作品")
                all_works.extend(illust_ids)

            # 获取小说作品
            if "novels" in body:
                novel_ids = list(body["novels"].keys())
                logger.info(f"发现{len(novel_ids)}个小说作品")
                all_works.extend(novel_ids)

            # 获取作品详细信息
            works_with_details = []

            for work_id in all_works:
                if work_id == str(author_id):  # 跳过作者ID本身
                    continue

                try:
                    # 判断是插画还是小说
                    if body.get("illusts", {}).get(work_id) is not None or work_id in body.get("illusts", {}):
                        # 这是插画
                        detail = self.get_illust_detail(int(work_id))
                        if detail:
                            detail["work_type"] = "illust"
                            works_with_details.append(detail)
                    elif body.get("novels", {}).get(work_id) is not None or work_id in body.get("novels", {}):
                        # 这是小说
                        detail = self.get_novel_detail(int(work_id))
                        if detail:
                            detail["work_type"] = "novel"
                            works_with_details.append(detail)

                except Exception as e:
                    logger.debug(f"获取作品{work_id}详情失败: {str(e)}")
                    continue

            logger.info(f"获取到作者{author_id}的{len(works_with_details)}个作品（包括插画和小说）")
            return works_with_details

        except Exception as e:
            logger.error(f"获取作者{author_id}作品时出错: {str(e)}")
            return []

    def get_illust_detail(self, illust_id: int) -> Optional[Dict]:
        """
        获取作品详细信息
        """
        try:
            url = f"https://www.pixiv.net/ajax/illust/{illust_id}"

            response = self.session.get(url)
            response.raise_for_status()

            data = response.json()

            if data.get("error"):
                logger.error(f"获取作品{illust_id}详情失败: {data.get('message')}")
                return None

            body = data.get("body", {})
            return {
                "illust_id": illust_id,
                "title": body.get("title", ""),
                "like_count": body.get("likeCount", 0),
                "bookmark_count": body.get("bookmarkCount", 0),
                "view_count": body.get("viewCount", 0),
                "comment_count": body.get("commentCount", 0),
                "create_date": body.get("createDate", ""),
                "tags": [tag.get("tag") for tag in body.get("tags", {}).get("tags", [])],
                "author_id": body.get("userId", 0),
                "fetch_time": time.time()
            }

        except Exception as e:
            logger.error(f"获取作品{illust_id}详情时出错: {str(e)}")
            return None

    def get_follower_count(self, author_id: int) -> int:
        """
        获取作者粉丝数
        """
        try:
            # 尝试从不同的API获取粉丝数
            urls = [
                f"https://www.pixiv.net/ajax/user/{author_id}/profile/top",
                f"https://www.pixiv.net/ajax/user/{author_id}/profile",
                f"https://www.pixiv.net/ajax/user/{author_id}"
            ]

            for url in urls:
                response = self.session.get(url)
                if response.status_code == 200:
                    data = response.json()
                    if not data.get("error"):
                        body = data.get("body", {})
                        logger.debug(f"粉丝数API返回 {url}: {str(body)[:300]}...")

                        # 尝试不同的可能字段名
                        follower_count = None

                        # 检查各种可能的粉丝数字段
                        if "userData" in body:
                            follower_count = body["userData"].get("followeeCount")
                            if follower_count is None:
                                follower_count = body["userData"].get("followerCount")

                        if follower_count is None:
                            follower_count = body.get("followeeCount")

                        if follower_count is None:
                            follower_count = body.get("followerCount")

                        if follower_count is None and "user" in body:
                            follower_count = body["user"].get("followerCount")

                        if follower_count is None and "profile" in body:
                            follower_count = body["profile"].get("followerCount")

                        if follower_count is not None:
                            logger.info(f"获取到作者{author_id}粉丝数: {follower_count}")
                            return int(follower_count)

            # 如果无法获取粉丝数，暂时返回0但记录日志
            logger.warning(f"无法获取作者{author_id}的粉丝数 - API可能不支持此功能")
            return 0

        except Exception as e:
            logger.error(f"获取作者{author_id}粉丝数时出错: {str(e)}")
            return 0

    def check_cookie_valid(self) -> bool:
        """
        检查Cookie是否有效
        """
        try:
            # 尝试访问Pixiv主页检查登录状态
            response = self.session.get("https://www.pixiv.net/")
            # 如果能正常访问主页，就认为Cookie基本有效
            return response.status_code == 200
        except Exception as e:
            logger.error(f"Cookie验证失败: {str(e)}")
            return False

    def get_novel_detail(self, novel_id: int) -> Optional[Dict]:
        """
        获取小说详细信息
        """
        try:
            url = f"https://www.pixiv.net/ajax/novel/{novel_id}"

            response = self.session.get(url)
            response.raise_for_status()

            # 检查响应内容是否为空
            if not response.text.strip():
                logger.warning(f"小说{novel_id}返回空响应")
                return None

            try:
                data = response.json()
            except ValueError as e:
                logger.error(f"解析小说{novel_id}JSON失败: {str(e)}")
                return None

            if data.get("error"):
                logger.error(f"获取小说{novel_id}详情失败: {data.get('message')}")
                return None

            body = data.get("body", {})
            return {
                "illust_id": novel_id,  # 保持字段名一致，便于统一处理
                "title": body.get("title", ""),
                "like_count": body.get("likeCount", 0),
                "bookmark_count": body.get("bookmarkCount", 0),
                "view_count": body.get("viewCount", 0),
                "comment_count": body.get("commentCount", 0),
                "create_date": body.get("createDate", ""),
                "tags": [tag.get("tag") for tag in body.get("tags", {}).get("tags", [])],
                "author_id": body.get("userId", 0),
                "fetch_time": time.time()
            }

        except Exception as e:
            logger.error(f"获取小说{novel_id}详情时出错: {str(e)}")
            return None

    def __delay_request(self):
        """请求延迟"""
        time.sleep(PIXIV_CONFIG["request_delay"])